//
//  OrderMoreVC.m
//  sensen_ios
//
//  Created by mc on 16/2/25.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "OrderMoreVC.h"



#import "OrderPayRequestHandle.h" // 支付
#import "PayOrderModel.h" // 支付订单model
#import "ConfirmPayVC.h"

#import "OrderProductDetailVC.h"

#import "OrderProductCell.h"

#import "LeftBtn.h"

#import "OrderModel.h"
#import "CartProductModel.h"

//快递详情
#import "WebViewController.h"

@interface OrderMoreVC ()<UITableViewDataSource, UITableViewDelegate>{
    NSInteger _curpage;//页码,默认0
    NSInteger _pageSize;//每页显示个数，默认10,最大30,最小1,
    NSInteger _status;
    NSString * _order_code;//订单编号
    
}

@property (nonatomic, strong) UITableView *tableView; // 表视图
@property (nonatomic, strong) UIView * emptyView;
@property (nonatomic, strong) NSMutableArray * dataArray;
@end

@implementation OrderMoreVC





- (void)viewDidLoad {
    [super viewDidLoad];
    _status = [self.order_state integerValue];
    NSLog(@"状态 ＝ %ld", (long)_status);
    [self _initTableView];
    [self _noHiddenTableView];
    [self _getData];
    
    // 下拉加载更多
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(_getData)];
    _tableView.header = header;
    self.view.backgroundColor = [UIColor whiteColor];
    
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];

}

// 创建表视图
- (void)_initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 36 - 64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [self _initNoDataView];
    
    
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;
}
//当没有数据时，隐藏表视图，显示没有数据图
- (void)_hiddenTableView{
    _tableView.hidden = YES;
    _emptyView.hidden = NO;
}

//当有数据时，显示表视图，隐藏没有数据图
- (void)_noHiddenTableView{
    _tableView.hidden = NO;
    _emptyView.hidden = YES;
}


// 创建没有订单视图
- (void)_initNoDataView{
    _emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 36 - 64)];
    _emptyView.backgroundColor = rgba(237, 238, 239, 1);
    [self.view addSubview:_emptyView];
    UIImageView * imageView = [[UIImageView alloc] init];
    imageView.image = [UIImage imageNamed:@"我的订单_没有数据"];
    [_emptyView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.centerX.equalTo(_emptyView.mas_centerX);
         make.size.mas_equalTo(CGSizeMake(80, 80));
         make.top.equalTo(_emptyView.mas_top).offset(SCREEN_HEIGHT / 4);
     }];
    
    
    UILabel * Label = [[UILabel alloc] init];
    [_emptyView addSubview:Label];
    [Label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_emptyView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(180, 25));
        make.top.equalTo(imageView.mas_bottom).offset(20);
    }];
    Label.text = @"您还没有相关订单";
    Label.textColor = SS_NAVI_ORANGE_COLOR;
    Label.textAlignment = NSTextAlignmentCenter;
    Label.font = [UIFont systemFontOfSize:15];
    
}



- (void)_getData {
    [SVProgressHUD showWithStatus:@"正在加载..."]; // 请求中
    _pageSize = 10;
    _curpage = 0;
    
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_status] forKey:@"status"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_curpage] forKey:@"curpage"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_pageSize] forKey:@"pageSize"];
    NSLog(@"%ld", (long)_status);
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_Orders_query" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        
        if (_dataArray == nil) {
            _dataArray = [[NSMutableArray alloc] init];
        } else {
            [_dataArray removeAllObjects];
        }
        NSLog(@"订单   %@", result);

        if ([result isKindOfClass:[NSString class]]) {
            if ([result isEqualToString:@""]) {
                [weakSelf _hiddenTableView];
            }
        }else{
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            NSDictionary *diction = result[@"list"];
            NSArray * keys = diction.allKeys;
            for (NSString * key in keys) {
                NSDictionary * dic = [diction objectForKey:key];
                OrderModel * model = [[OrderModel alloc] initContentWithDic:dic];
                model.order_id = dic[@"id"];
                model._items = [NSMutableArray array];
                NSMutableArray * items = dic[@"_items"];
                for (int i = 0; i < items.count; i++) {
                    NSDictionary *itemsDic = [items objectAtIndex:i];
                    CartProductModel *item = [[CartProductModel alloc] initContentWithDic:itemsDic];
                    [model._items addObject:item];
                }
                [weakSelf.dataArray addObject:model];
            }
        }
            
        }
        [SVProgressHUD dismiss];
        [_tableView.header endRefreshing]; // 结束刷新
        weakSelf.dataArray = [weakSelf ArraySort:weakSelf.dataArray];
        [weakSelf.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          [_tableView.header endRefreshing]; // 结束刷新
         [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:2];
    }];

   
}


- (void)_getMoreData {
    [SVProgressHUD showWithStatus:@"正在加载...."]; // 请求中
    _pageSize += 1;
    _curpage = 10;
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_status] forKey:@"status"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_curpage] forKey:@"curpage"];
    [diction setObject:[NSString stringWithFormat:@"%ld", (long)_pageSize] forKey:@"pageSize"];
    
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_Orders_query" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"加载更多中  %@", result);
        if ([result isKindOfClass:[NSString class]]) {
            
        }else{
        if (![result[@"list"] isKindOfClass:[NSNull class]]) { // 有数据
            NSDictionary *diction = result[@"list"];
            NSArray * keys = diction.allKeys;
            for (NSString * key in keys) {
                NSDictionary * dic = [diction objectForKey:key];
                OrderModel * model = [[OrderModel alloc] initContentWithDic:dic];
                model.order_id = dic[@"id"];
                model._items = [NSMutableArray array];
                NSMutableArray * items = dic[@"_items"];
                for (int i = 0; i < items.count; i++) {
                    NSDictionary *itemsDic = [items objectAtIndex:i];
                    CartProductModel *item = [[CartProductModel alloc] initContentWithDic:itemsDic];
                    [model._items addObject:item];
                }
                
                [weakSelf.dataArray addObject:model];
            }
        }
            
    }
    
     [SVProgressHUD dismiss];
     [_tableView.footer endRefreshing];
     weakSelf.dataArray = [weakSelf ArraySort:weakSelf.dataArray];
     [weakSelf.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_tableView.footer endRefreshing];
        [SVProgressHUD showErrorWithStatus:@"请求失败" withDuration:2];
    }];

    
}

//排序
-(NSMutableArray *)ArraySort:(NSMutableArray *)list{
    if (list.count == 0 || list.count == 1) {
        return list;
    }
    
    int i,j;
    //两重for循环对数组进行比较和交换
    for(i = 0;i < list.count - 1;i++)
    {
        for(j = i+1;j < list.count;j++){
            OrderModel * model1 = [list objectAtIndex:i];
            OrderModel * model2 = [list objectAtIndex:j];

            if([model1.updatetime longLongValue] < [model2.updatetime longLongValue]){
                 [list exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
    }
    return list;
}




//订单确认收货
- (void)requestOrderSure{
    [SVProgressHUD showWithStatus:@"订单处理中...."]; // 请求中
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:_order_code forKey:@"order_code"];
    __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_Orders_sureorder" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        [SVProgressHUD showOnlyStatus:@"订单确认收货" withDuration:1];
        [weakSelf _getData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"失败，请重试" withDuration:2];
    }];

}

//订单取消
- (void)requestOrderQx{
    [SVProgressHUD showWithStatus:@"订单处理中...."]; // 请求中
    NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
    UserModel *user = [CommonCache getUserInfo];
    [diction setObject:user.uid forKey:@"uid"];
    [diction setObject:_order_code forKey:@"order_code"];
     __weak typeof (self) weakSelf = self;
    [BoyeHttpClient post:@"BY_Orders_qxorder" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
        [SVProgressHUD showOnlyStatus:@"订单取消" withDuration:1];
        [weakSelf _getData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"失败，请重试" withDuration:2];
    }];

}



#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    OrderModel * model = [self.dataArray objectAtIndex:section];
    if (([model.order_status integerValue] == 3 || [model.order_status integerValue] == 2) && [model.pay_status integerValue] == 1) {//待发货
        return model._items.count + 1;
    }else{
        return model._items.count + 2;
    }
    
}

// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    OrderModel * model = [self.dataArray objectAtIndex:indexPath.section];
    NSLog(@"%@ %@",model.order_status, model.pay_status);
    
    if (indexPath.row < model._items.count) {
        CartProductModel * item = [model._items objectAtIndex:indexPath.row];
        OrderProductCell *cell = [OrderProductCell cellWithTableView:tableView];
        [cell.ivContent setImageURLStr:item.img_url placeholder:DEFAULT_IMAGE];
        cell.lblTitle.text = item.name;
        cell.lblBrand.text = item.sku_desc;
        cell.lblPrice.text = [NSString stringWithFormat:@"¥%@", item.price];
        cell.lblCount.text = [NSString stringWithFormat:@"X %@", item.count];
        
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if (indexPath.row == model._items.count){

        static NSString * cellIdentifier = @"Cell1";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell ==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

        }
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }

        
        UILabel * lable = [[UILabel alloc] init];
        lable.textAlignment = NSTextAlignmentRight;
        [cell.contentView addSubview:lable];
        [lable mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView).offset(0);
            make.bottom.equalTo(cell.contentView).offset(-0.5);
            make.right.equalTo(cell.contentView).offset(-10);
            make.left.equalTo(cell.contentView).offset(10);
        }];
        
        
        NSInteger count = 0;
        for (CartProductModel * temp in model._items) {
            count += [temp.count integerValue];
        }
        int discount_money  = [model.discount_money intValue];
        if (discount_money > 0) {
            lable.text = [NSString stringWithFormat:@"共%ld件商品 合计:¥%@(优惠¥%@，含运费¥%@)", (long)count, model.price, model.discount_money, model.post_price];
        }else{
            lable.text = [NSString stringWithFormat:@"共%ld件商品 合计:¥%@(含运费¥%@)", (long)count, model.price, model.post_price];
        }

        lable.textColor = [UIColor darkGrayColor];
        lable.font = [UIFont systemFontOfSize:13];
        lable.adjustsFontSizeToFitWidth = YES;
        if (([model.order_status integerValue] == 3 || [model.order_status integerValue] == 2) && [model.pay_status integerValue] == 1) {//待发货
            //加条线
            UILabel * lable2 = [[UILabel alloc] init];
            [cell.contentView addSubview:lable2];
            [lable2 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(cell.contentView).offset(0);
                make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 0.5));
                make.bottom.equalTo(cell.contentView.mas_bottom).offset(-0.5);
            }];
            lable2.backgroundColor = [UIColor colorWithRGBHex:0xd9d9d9];
        }

        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
        
        //第三行添加按钮
    }else{
        static NSString * cellIdentifier = @"Cell2";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell ==nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            
    }
        

        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
           //加条线
           UILabel * lable = [[UILabel alloc] init];
           [cell.contentView addSubview:lable];
           [lable mas_makeConstraints:^(MASConstraintMaker *make) {
               make.left.equalTo(cell.contentView).offset(0);
               make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 0.5));
               make.bottom.equalTo(cell.contentView.mas_bottom).offset(-0.5);
           }];
           lable.backgroundColor = [UIColor colorWithRGBHex:0xd9d9d9];
            //付款
            UIButton *payBtn = [UIButton buttonWithType:UIButtonTypeSystem];
            payBtn.bounds = CGRectMake(0, 0, 50, 25);
            payBtn.layer.borderColor = SS_NAVI_ORANGE_COLOR.CGColor;
            [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            payBtn.layer.borderWidth = 1;
            payBtn.layer.masksToBounds = YES;
            payBtn.layer.cornerRadius = 3.0;
            [payBtn setBackgroundColor:SS_NAVI_ORANGE_COLOR];
            [payBtn setTitle:@"付款" forState:UIControlStateNormal];
            payBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            
            //提醒卖家发货
            UIButton *remindBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            remindBtn.bounds = CGRectMake(0, 0, 120, 25);
            remindBtn.layer.borderColor = SS_NAVI_ORANGE_COLOR.CGColor;
            [remindBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            remindBtn.layer.borderWidth = 1;
            remindBtn.layer.masksToBounds = YES;
            remindBtn.layer.cornerRadius = 3.0;
            [remindBtn setBackgroundColor:SS_NAVI_ORANGE_COLOR];
            [remindBtn setTitle:@"提醒卖家发货" forState:UIControlStateNormal];
            remindBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        
           //待付款
         if ([model.order_status integerValue] == 2 && [model.pay_status integerValue] == 0) {//待付款
            LeftBtn *cancelBtn = [LeftBtn buttonWithType:UIButtonTypeCustom];
            [cancelBtn setTitle:@"取消订单" forState:UIControlStateNormal];
            [cell.contentView addSubview:cancelBtn];
            [cell.contentView addSubview:payBtn];
            
            [payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(40, 25));
                make.right.equalTo(cell.contentView.mas_right).offset(-10);
            }];
            
            
            [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(80, 25));
                make.right.equalTo(payBtn.mas_left).offset(-10);
            }];
            
            [payBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
            [cancelBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
            
            
            
        }
        //待收货状态
        else if ([model.order_status integerValue] == 4 && [model.pay_status integerValue] == 1){//待收货
            
            
            LeftBtn *confirmBtn = [LeftBtn buttonWithType:UIButtonTypeCustom];
            [cell.contentView addSubview:confirmBtn];
            [confirmBtn setTitle:@"确认收货" forState:UIControlStateNormal];
            [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(80, 25));
                make.right.equalTo(cell.contentView.mas_right).offset(-10);
            }];
            [confirmBtn setBackgroundColor:SS_NAVI_ORANGE_COLOR];
            [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            confirmBtn.layer.borderColor = SS_NAVI_ORANGE_COLOR.CGColor;
            [confirmBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
            
            
            LeftBtn *logisticsBtn = [LeftBtn buttonWithType:UIButtonTypeCustom];
            [cell.contentView addSubview:logisticsBtn];
            [logisticsBtn setTitle:@"查看物流" forState:UIControlStateNormal];
            [logisticsBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(80, 25));
                make.right.equalTo(confirmBtn.mas_left).offset(-10);
            }];
            [logisticsBtn  addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
            
            
            
        }else if ([model.order_status integerValue] == 8 && [model.pay_status integerValue] == 0){//交易关闭
            LeftBtn *cancelBtn = [LeftBtn buttonWithType:UIButtonTypeCustom];
            [cancelBtn setTitle:@"交易关闭" forState:UIControlStateNormal];
            [cell.contentView addSubview:cancelBtn];
            [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(80, 25));
                make.right.equalTo(cell.contentView.mas_right).offset(-10);
            }];
            cancelBtn.layer.borderColor = [UIColor whiteColor].CGColor;
            cancelBtn.titleLabel.textColor = [UIColor lightGrayColor];
            [cancelBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];

        }else if ([model.order_status integerValue] == 7 && [model.pay_status integerValue] == 1){//交易完成
            LeftBtn *cancelBtn = [LeftBtn buttonWithType:UIButtonTypeCustom];
            [cancelBtn setTitle:@"交易完成" forState:UIControlStateNormal];
            [cell.contentView addSubview:cancelBtn];
            [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(80, 25));
                make.right.equalTo(cell.contentView.mas_right).offset(-10);
            }];
            cancelBtn.layer.borderColor = [UIColor whiteColor].CGColor;
            cancelBtn.titleLabel.textColor = [UIColor lightGrayColor];
            [cancelBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
            
        }else if ([model.order_status integerValue] == 5 && [model.pay_status integerValue] == 1){//已收货
            LeftBtn *cancelBtn = [LeftBtn buttonWithType:UIButtonTypeCustom];
            [cancelBtn setTitle:@" 已收货" forState:UIControlStateNormal];
            [cell.contentView addSubview:cancelBtn];
            [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(80, 25));
                make.right.equalTo(cell.contentView.mas_right).offset(-10);
            }];
            cancelBtn.layer.borderColor = [UIColor whiteColor].CGColor;
            cancelBtn.titleLabel.textColor = [UIColor lightGrayColor];
            [cancelBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
            
        }else{
            LeftBtn *cancelBtn = [LeftBtn buttonWithType:UIButtonTypeCustom];
            [cancelBtn setTitle:@"交易完成" forState:UIControlStateNormal];
            [cell.contentView addSubview:cancelBtn];
            [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contentView.mas_centerY);
                make.size.mas_equalTo(CGSizeMake(80, 25));
                make.right.equalTo(cell.contentView.mas_right).offset(-10);
            }];
            cancelBtn.layer.borderColor = [UIColor whiteColor].CGColor;
            cancelBtn.titleLabel.textColor = [UIColor lightGrayColor];
            [cancelBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];

        }

        
        
        [remindBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
        [payBtn addTarget:self action:@selector(btnAction:event:) forControlEvents:UIControlEventTouchUpInside];
        /* 忽略点击效果 */
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
}


// 设置单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OrderModel * model = [self.dataArray objectAtIndex:indexPath.section];
    if (indexPath.row < model._items.count) {
        return 75;
        
    }else if (indexPath.row == model._items.count){
        
        return 30;
    }else{
        return 44;
    }
    
}
// 设置组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == self.dataArray.count - 1) {
        return 5;
    }else{
        return 10;
    }
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == self.dataArray.count - 1) {
        return nil;
    }else{
        UIView * view = [[UIView alloc] init];
        view.backgroundColor = [BoyeTool colorFromHexRGB:@"#f5f5f5"];
        return view;
        
    }
}



// 设置组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 15;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
        UIView * view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        return view;
    
}



- (void)btnAction:(UIButton *)button event:(UIEvent*)event{
    UITouch * touch = [[event allTouches] anyObject];
    CGPoint point = [touch locationInView:self.tableView];
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
    OrderModel * model = [self.dataArray objectAtIndex:indexPath.section];
    _order_code = model.order_code;
    NSString *title = [button titleForState:UIControlStateNormal];
    if ([title isEqualToString:@"联系客服"]) {
        NSLog(@"联系客服");
    }
    else if ([title isEqualToString:@"取消订单"]){
        NSLog(@"取消订单");
        [self requestOrderQx];
    }
    else if ([title isEqualToString:@"付款"]){
        NSLog(@"付款");
         [SVProgressHUD showWithStatus:@"订单处理中...."]; // 请求中
        NSMutableDictionary *  diction = [NSMutableDictionary dictionaryWithCapacity:0];
        UserModel *user = [CommonCache getUserInfo];
        [diction setObject:user.uid forKey:@"uid"];
        [diction setObject:model.order_id forKey:@"order_id"];
        [BoyeHttpClient post:@"BY_Orders_pay" apiVerson:100 params:diction success:^(AFHTTPRequestOperation *operation, id result) {
            NSLog(@"%@" , result);
            [SVProgressHUD dismiss];
            // 创建支付订单model
            PayOrderModel *payOrderModel = [[PayOrderModel alloc] initContentWithDic:result];
            
            // 添加订单成功后，跳转到选择支付页面
            ConfirmPayVC *vc = [[ConfirmPayVC alloc] init];
            vc.payOrderModel = payOrderModel;
            
            [self.navigationController pushViewController:vc animated:YES];

    
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:1];
        }];

        
        
       
       
        
        
    }
    else if ([title isEqualToString:@"延长收货"]){
        NSLog(@"延长收货");
    }
    else if ([title isEqualToString:@"查看物流"]){
        NSLog(@"查看物流");
        
       
        
        WebViewController *webVC = [[WebViewController alloc] initWithUrlString:[NSString stringWithFormat:@"%@/Express/viewOrder?order_code=%@",WEB_BASE_URL,model.order_code]];
        webVC.titleString = @"物流详情";
        [self.navigationController pushViewController:webVC animated:YES];
    
    
        
    }
    else if ([title isEqualToString:@"确认收货"]){
        
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
            
            // 创建警告弹窗
            NSString *alertTitle = @"确定要确认收货？";
            NSString *yesButtonTitle = @"确定";
            NSString *cancelButtonTitle = @"取消";
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            // 添加点击动作
            // 取消
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:nil];
            // 确定
            UIAlertAction *yesAction = [UIAlertAction actionWithTitle:yesButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action)
                                        {
                                            //确认收货
                                            [self requestOrderSure];
                                        }];
            
            // Add the actions.
            [alertController addAction:cancelAction];
            [alertController addAction:yesAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
        else{
            //确认收货
            [self requestOrderSure];
        }

        
        
        
       
    }
    else if ([title isEqualToString:@"提醒卖家发货"]){
        NSLog(@"提醒卖家发货");
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];// 取消选中阴影
    OrderModel * model = [self.dataArray objectAtIndex:indexPath.section];
    
    if ([model.order_status integerValue] == 8 && [model.pay_status integerValue] == 0) {//交易关闭
        [SVProgressHUD showOnlyStatus:@"交易关闭不能查看详情" withDuration:1];
        return;
    }
    
    
    
    if (indexPath.row < model._items.count) {
        OrderProductDetailVC *vc = [[OrderProductDetailVC alloc] init];
        vc.order_id = model.order_id;
        vc.order_code = model.order_code;
        [self.navigationController pushViewController:vc animated:YES];

    }
}




#pragma mark 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
